package com.share.servlet;

import com.share.servlet.pojo.User;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.Enumeration;
import java.util.Map;

/*
一、HttpServletRequest 也是一个域对象
    1、getAttribute()、setAttribute()
 */
public class demo2_form extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //告诉服务器客户端用什么编码，服务器默认用ISO-8859-8

//        String str = new String(req.getParameter("userName").getBytes("iso-8859-1"), "utf-8");
//        System.out.println("uername: " + str);
//
//        System.out.println("client-encoding: " + req.getCharacterEncoding());
//        req.setCharacterEncoding("UTF-8");
//
//        String userName = req.getParameter("userName");
//        String pwd = req.getParameter("pwd");
//        String sex = req.getParameter("sex");
//        String city = req.getParameter("city");
//        String[] hobby = req.getParameterValues("hobby");
//
//        System.out.println(userName);
//        System.out.println(pwd);
//        System.out.println(sex);
//        System.out.println(city);
//        System.out.println(hobby);



    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");//只能解决post方式的乱码
//        test1(req);
        try {
            User u = new User();
            System.out.println("封装数据前："+u);
            Map map = req.getParameterMap();
            BeanUtils.populate(u, map);
            System.out.println("封装数据后："+u);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    private void test1(HttpServletRequest req) throws UnsupportedEncodingException {
        //告诉服务器客户端用什么编码，服务器默认用ISO-8859-8

//        String str = new String(req.getParameter("userName").getBytes("iso-8859-1"), "utf-8");
//        System.out.println("uername: " + str);

        String userName = req.getParameter("userName");
        String pwd = req.getParameter("pwd");
        String sex = req.getParameter("sex");
        String city = req.getParameter("city");
        String[] hobby = req.getParameterValues("hobby");

        System.out.println(userName);
        System.out.println(pwd);
        System.out.println(sex);
        System.out.println(city);
        System.out.println(hobby);
    }
}
